import { useUserStore } from '@/store/modules/user'

// 基础URL，可根据环境切换，需要替换项目中的地址
const baseURL = 'https://demo.hnedu123.com.cn/requestApi'

// 请求拦截器
const requestInterceptor = (options) => {
  const userStore = useUserStore()
  
  // 拼接完整URL
  if (!options.url.startsWith('http')) {
    options.url = baseURL + options.url
  }
  
  // 设置默认请求头
  options.header = {
    'Content-Type': 'application/json',
    ...options.header
  }
  
  // 添加token
  if (userStore.token) {
    options.header.Authorization = `Bearer ${userStore.token}`
  }
  
  return options
}

// 响应拦截器
const responseInterceptor = (response) => {
  const { data, statusCode } = response
  
  // 服务器成功响应
  if (statusCode === 200) {
    // 自定义业务错误处理
    if (data.code !== 0) {
      // 未登录，需要重新登录
      if (data.code === 401) {
        const userStore = useUserStore()
        userStore.logout()
        uni.navigateTo({ url: '/pages/login/index' })
      }
      
      // 显示错误信息
      uni.showToast({
        title: data.message || '请求失败',
        icon: 'none',
        duration: 3000
      })
      
      return Promise.reject(data)
    }
    
    return data.data
  }
  
  // HTTP错误处理
  uni.showToast({
    title: `HTTP错误: ${statusCode}`,
    icon: 'none',
    duration: 3000
  })
  
  return Promise.reject(response)
}

// 错误处理
const requestError = (error) => {
  uni.showToast({
    title: '网络请求失败',
    icon: 'none',
    duration: 3000
  })
  return Promise.reject(error)
}

// 封装请求方法
export const request = (options) => {
  // 应用请求拦截器
  const reqOptions = requestInterceptor(options)
  
  return new Promise((resolve, reject) => {
    uni.request({
      ...reqOptions,
      success: (response) => {
        try {
          const result = responseInterceptor(response)
          resolve(result)
        } catch (err) {
          reject(err)
        }
      },
      fail: (error) => {
        const err = requestError(error)
        reject(err)
      }
    })
  })
}

// 快捷请求方法
export const http = {
  get(url, data = {}, options = {}) {
    return request({
      url,
      data,
      method: 'GET',
      ...options
    })
  },
  
  post(url, data = {}, options = {}) {
    return request({
      url,
      data,
      method: 'POST',
      ...options
    })
  },
  
  put(url, data = {}, options = {}) {
    return request({
      url,
      data,
      method: 'PUT',
      ...options
    })
  },
  
  delete(url, data = {}, options = {}) {
    return request({
      url,
      data,
      method: 'DELETE',
      ...options
    })
  }
}

export default http
